<?php


namespace app\service;

use app\model\ArticleCollectModel;
use think\facade\Request;
use \app\model\ArticleModel;
use \app\model\ArticleLikeModel;

use think\response\Json;

class articleService
{
    public $request;

    public function __construct(Request $request)
    {
        $this->$request = $request;
    }

    // 获取所有文章
    public static function getArticle(array $data, array $page, $queryTime): Json
    {
        //过滤空值
        $newData = [];
        if (count($data) > 0) {
            $newData = array_filter($data);
        }

        $article = new ArticleModel();
        try {
            $result = $article->with(['articleUser', 'articleType', 'articleDiscuss'])
                ->order('issueTime', 'desc')
                ->where($newData)
                ->whereTime('issueTime', '>=', $queryTime['issueTime'])
                ->paginate($page);

            return \json(['code' => 200, 'data' => $result,], 200);
        } catch (\Exception $e) {
            return json($e->getMessage(), 500);
        };
    }

    // 添加文章 和更新 文章
    public static function addAndUpdateArticle(array $data): Json
    {
        try {
            $result[] = [];

            if (array_key_exists('id', $data)) {
                ArticleModel::find($data['id'])->save($data);
                $result = ['msg' => '修改成功', 'code' => 200];
            } else {
                ArticleModel::create($data);
                $result = ['msg' => '添加成功', 'code' => 200];
            }

            return \json($result, 200);
        } catch (\Exception $e) {
            return json($e->getMessage(), 500);
        };
    }

    // 文章点赞
    public static function Link(array $data): Json
    {
        try {
            $result = ArticleLikeModel::create($data);
            if (!$result->isEmpty()) {
                return json(['msg' => '点赞成功', 'code' => 200], 200);
            }
        } catch (\Exception $e) {
            return \json($e->getMessage(), $e->getCode());
        }
    }

    // 文章收藏
    public static function collect(array $data): Json
    {
        try {
            $result = ArticleCollectModel::create($data);
            if (!$result->isEmpty()) {
                return json(['msg' => '收藏成功', 'code' => 200], 200);
            }
        } catch (\Exception $e) {
            return \json($e->getMessage(), $e->getCode());
        }
    }


}